
import React, { useEffect, useRef, useState } from 'react'
import { Button, Input, Form, Toast, Tabs } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import { authManager } from '../../utils/auth'
import { api } from '../../utils/request'
import './login.css'

interface LoginFormData {
  username: string
  password: string
  code: string
}

interface LoginProps {}

const Login: React.FC<LoginProps> = () => {
  const [form] = Form.useForm<LoginFormData>()
  const [loading, setLoading] = useState<boolean>(false)
  const [loginType, setLoginType] = useState<'password' | 'sms'>('password')
  const [sending, setSending] = useState<boolean>(false)
  const [secondsLeft, setSecondsLeft] = useState<number>(0)
  const timerRef = useRef<number | null>(null)
  const navigate = useNavigate()

  const COUNTDOWN_SECONDS = 60
  const isCounting = secondsLeft > 0

  // 倒计时逻辑
  useEffect(() => {
    if (!isCounting) return
    timerRef.current = window.setInterval(() => {
      setSecondsLeft((s) => {
        if (s <= 1) {
          if (timerRef.current) window.clearInterval(timerRef.current)
          return 0
        }
        return s - 1
      })
    }, 1000)
    return () => {
      if (timerRef.current) window.clearInterval(timerRef.current)
    }
  }, [isCounting])

  // 发送验证码
  const handleSendCode = async (): Promise<void> => {
    const phone = form.getFieldValue('username')
    if (!phone || String(phone).trim().length !== 11) {
      Toast.show({ icon: 'fail', content: '请先填写正确的手机号' })
      return
    }
    if (isCounting) return
    try {
      setSending(true)
      const resp = await fetch('http://localhost:5000/api/auth/send-code', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phone })
      })
      const data = await resp.json()
      if (!resp.ok) {
        throw new Error(data?.message || '发送验证码失败')
      }
      Toast.show({ icon: 'success', content: '验证码已发送' })
      setSecondsLeft(COUNTDOWN_SECONDS)
    } catch (e) {
      Toast.show({ icon: 'fail', content: (e as Error).message || '发送验证码失败' })
    } finally {
      setSending(false)
    }
  }

  // 密码登录
  const handlePasswordLogin = async (values: LoginFormData): Promise<void> => {
    setLoading(true)
    
    try {
      const resp = await api.post('http://localhost:5000/api/auth/login', {
        phone: values.username,
        password: values.password
      })
      
      const data = await resp.json()
      if (!resp.ok) {
        throw new Error(data?.message || '登录失败')
      }
      
      // 保存双token和用户信息
      authManager.setTokens({
        accessToken: data.accessToken,
        refreshToken: data.refreshToken,
        expiresIn: data.expiresIn
      })
      authManager.setUserInfo({
        id: data.id,
        phone: data.phone
      })

      Toast.show({ icon: 'success', content: '登录成功' })
      navigate('/guide')
    } catch (error) {
      Toast.show({
        icon: 'fail',
        content: (error as Error).message || '登录失败，请重试',
      })
    } finally {
      setLoading(false)
    }
  }

  // 短信登录
  const handleSmsLogin = async (values: LoginFormData): Promise<void> => {
    setLoading(true)
    
    try {
      const resp = await api.post('http://localhost:5000/api/auth/sms-login', {
        phone: values.username,
        code: values.code
      })
      
      const data = await resp.json()
      if (!resp.ok) {
        throw new Error(data?.message || '登录失败')
      }
      
      // 保存双token和用户信息
      authManager.setTokens({
        accessToken: data.accessToken,
        refreshToken: data.refreshToken,
        expiresIn: data.expiresIn
      })
      authManager.setUserInfo({
        id: data.id,
        phone: data.phone
      })

      Toast.show({ icon: 'success', content: '登录成功' })
      navigate('/guide')
    } catch (error) {
      Toast.show({
        icon: 'fail',
        content: (error as Error).message || '登录失败，请重试',
      })
    } finally {
      setLoading(false)
    }
  }

  const handleLogin = async (values: LoginFormData): Promise<void> => {
    console.log('登录类型:', loginType)
    console.log('表单数据:', values)
    
    // 根据登录类型验证不同字段
    if (loginType === 'password') {
      if (!values.username || !values.password) {
        Toast.show({ icon: 'fail', content: '请填写完整信息' })
        return
      }
      await handlePasswordLogin(values)
    } else {
      if (!values.username || !values.code) {
        Toast.show({ icon: 'fail', content: '请填写完整信息' })
        return
      }
      await handleSmsLogin(values)
    }
  }

  const handleRegister = (): void => {
    navigate('/register')
  }

  const handleForgotPassword = (): void => {
    Toast.show({
      content: '忘记密码功能暂未开放',
    })
  }

 
  return (
    <div className="login-container">
      <div className="login-header">
        <h1 className="login-title">欢迎回来</h1>
        <p className="login-subtitle">登录您的健身账户</p>
      </div>

      <Tabs
        activeKey={loginType}
        onChange={(key) => {
          setLoginType(key as 'password' | 'sms')
          form.resetFields()
        }}
        className="login-tabs"
      >
        <Tabs.Tab title="密码登录" key="password">
          <Form
            form={form}
            onFinish={handleLogin}
            layout="vertical"
            className="login-form"
            initialValues={{ username: '', password: '' }}
          >
            <Form.Item
              name="username"
              label="手机号"
              rules={[
                { required: true, message: '请输入手机号' },
                { len: 11, message: '手机号必须为11位' }
              ]}
            >
              <Input
                placeholder="请输入手机号"
                clearable
              />
            </Form.Item>

            <Form.Item
              name="password"
              label="密码"
              rules={[
                { required: true, message: '请输入密码' },
                { min: 6, message: '密码至少6个字符' }
              ]}
            >
              <Input
                placeholder="请输入密码"
                type="password"
                clearable
              />
            </Form.Item>

            <div className="login-actions">
              <Button
                color="primary"
                size="large"
                block
                loading={loading}
                className="login-button"
                onClick={() => form.submit()}
              >
                登录
              </Button>
            </div>
          </Form>
        </Tabs.Tab>

        <Tabs.Tab title="短信登录" key="sms">
          <Form
            form={form}
            onFinish={handleLogin}
            layout="vertical"
            className="login-form"
            initialValues={{ username: '', code: '' }}
            validateTrigger={[]}
          >
            <Form.Item
              name="username"
              label="手机号"
              rules={[
                { required: true, message: '请输入手机号' },
                { len: 11, message: '手机号必须为11位' }
              ]}
            >
              <Input
                placeholder="请输入手机号"
                clearable
              />
            </Form.Item>

            <Form.Item
              name="code"
              label="验证码"
              rules={[
                { required: true, message: '请输入验证码' },
                { len: 4, message: '验证码为4位数字' }
              ]}
            >
              <div className="code-row">
                <Input
                  placeholder="请输入验证码"
                  clearable
                />
                <Button
                  size="mini"
                  color="primary"
                  fill="outline"
                  className="send-code-btn"
                  onClick={handleSendCode}
                  disabled={isCounting || sending}
                >
                  {isCounting ? `${secondsLeft}s` : '发送验证码'}
                </Button>
              </div>
            </Form.Item>

            <div className="login-actions">
              <Button
                color="primary"
                size="large"
                block
                loading={loading}
                className="login-button"
                onClick={async () => {
                  console.log('短信登录按钮点击')
                  const username = form.getFieldValue('username')
                  const code = form.getFieldValue('code')
                  console.log('获取到的值:', { username, code })
                  
                  if (!username || !code) {
                    Toast.show({ icon: 'fail', content: '请填写完整信息' })
                    return
                  }
                  
                  await handleSmsLogin({ username, code, password: '' })
                }}
              >
                登录
              </Button>
            </div>
          </Form>
        </Tabs.Tab>
      </Tabs>

      <div className="login-links">
        <Button
          fill="none"
          size="small"
          onClick={handleForgotPassword}
          className="forgot-password-link"
        >
          忘记密码？
        </Button>
      </div>

      <div className="register-section">
        <span className="register-text">还没有账号？</span>
        <span
          onClick={handleRegister}
          style={{ 
            color: 'white', 
            fontSize: '14px',
            fontWeight: '600',
            cursor: 'pointer',
            textDecoration: 'underline'
          }}
        >
          立即注册
        </span>
      </div>
    </div>
  )
}

export default Login